<template>
  <div class="container">
    <el-dialog :title="`${data.id ? '修改':'新增'}学科`" :visible.sync="dialogVisible" width="30%">
      <el-form
        ref="form"
        :model="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="学科名称" prop="subjectName">
          <el-input placeholder="请输入学科名称" v-model="ruleForm.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="ruleForm.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdd()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '../../api/hmmm/subjects'
export default {
  props: {
    data: {
      type: Object
    }
  },
  data () {
    return {
      dialogVisible: false,
      ruleForm: {
        id: null,
        subjectName: null,
        isFrontDisplay: 1
      },
      rules: {
        subjectName: [{ required: true, message: '请输入学科名称', trigger: 'blur' }],
        isDisplay: [{ type: 'number', message: '请选择是否显示', trigger: 'blur' }]
      }
    }
  },
  methods: {
    open () {
      this.dialogVisible = true
      if (this.data.id) {
        const { id, subjectName, isFrontDisplay } = this.data
        this.ruleForm = { id, subjectName, isFrontDisplay }
      } else {
        this.ruleForm = {
          id: null,
          subjectName: null,
          isFrontDisplay: 1
        }
      }
    },
    async submitAdd () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (!this.data.id) {
            await add(this.ruleForm)
            // console.log(111)
            this.$message.success('添加成功')
          } else {
            this.ruleForm.id = this.data.id
            await update(this.ruleForm)
            this.$message.success('修改成功')
          }
          this.dialogVisible = false
          this.$emit('updateList')
        }
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
